package ohc.login

import net.minecraft.server.MinecraftServer
import net.minecraft.text.Text

/**
 * 欢迎词管理
 */
object WelcomeManager {
    
    // Key: API UID, Value: 欢迎消息
    private val welcomeMessages: MutableMap<String, String> = mutableMapOf()
    
    fun getDataForSave(): Map<String, String> = welcomeMessages.toMap()
    
    fun loadFromData(data: Map<String, String>) {
        welcomeMessages.clear()
        welcomeMessages.putAll(data)
        if (welcomeMessages.isNotEmpty()) {
            Ohc_login.logger.info("已加载 ${welcomeMessages.size} 条欢迎词")
        }
    }
    
    /**
     * 设置欢迎词
     */
    fun setWelcome(apiUid: Long, message: String) {
        welcomeMessages[apiUid.toString()] = message
        PlayerDataManager.save()
    }
    
    /**
     * 删除欢迎词
     */
    fun removeWelcome(apiUid: Long): Boolean {
        val removed = welcomeMessages.remove(apiUid.toString())
        if (removed != null) {
            PlayerDataManager.save()
            return true
        }
        return false
    }
    
    /**
     * 获取欢迎词
     */
    fun getWelcome(apiUid: Long): String? {
        return welcomeMessages[apiUid.toString()]
    }
    
    /**
     * 全服播报欢迎词
     */
    fun broadcastWelcome(server: MinecraftServer, apiUid: Long, playerName: String) {
        val msg = welcomeMessages[apiUid.toString()] ?: return
        
        // 替换占位符
        val finalMsg = msg.replace("{player}", playerName)
        
        // 给所有玩家发送聊天消息
        server.playerManager.broadcast(Text.literal("§e$finalMsg"), false)
        
        Ohc_login.logger.info("播报欢迎词: $finalMsg (玩家: $playerName)")
    }
    
    /**
     * 获取所有欢迎词
     */
    fun getAllWelcomes(): Map<Long, String> {
        return welcomeMessages.mapKeys { it.key.toLong() }
    }
}
